using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

namespace InventorySystem.UI
{
    public class UI_InventorySlot : MonoBehaviour
    {
        // 物品栏
        [SerializeField]
        private Inventory _inventory;
        // 物品槽索引
        [SerializeField]
        private int _inventorySlotIndex;
        // 物品图标
        [SerializeField]
        private Image _itemIcon;
        // 激活指示器
        [SerializeField]
        private Image _activeIndicator;
        // 物品数量文本
        [SerializeField]
        private TMP_Text _numberOfItems;
        // 物品槽
        private InventorySlot _slot;

        private void Start()
        {
            AssignSlot(_inventorySlotIndex);
        }

        // 分配物品槽
        public void AssignSlot(int slotIndex)
        {
            // 取消之前的事件监听
            if (_slot != null) _slot.StateChanged -= OnStateChanged;

            // 更新物品槽索引
            _inventorySlotIndex = slotIndex;

            // 获取所属的物品栏
            if (_inventory == null) _inventory = GetComponentInParent<UI_Inventory>().Inventory;

            // 获取物品槽
            _slot = _inventory.Slots[_inventorySlotIndex];

            // 添加事件监听
            _slot.StateChanged += OnStateChanged;

            // 更新视图状态
            UpdateViewState(_slot.State, _slot.Active);
        }

        // 更新视图状态
        private void UpdateViewState(ItemStack state, bool active)
        {
            // 更新激活指示器
            _activeIndicator.enabled = active;

            var item = state?.Item;
            var hasItem = item != null;
            var isStackable = hasItem && item.IsStackable;

            // 更新物品图标显示
            _itemIcon.enabled = hasItem;

            // 更新物品数量文本显示
            _numberOfItems.enabled = isStackable;

            if (!hasItem) return;

            // 更新物品图标
            _itemIcon.sprite = item.UiSprite;

            if (isStackable)
            {
                // 更新物品数量文本
                _numberOfItems.SetText(state.NumberOfItems.ToString());
            }
        }

        // 物品槽状态改变事件处理方法
        // private void OnStateChanged(object sender, InventorySlotStateChangedArgs args)
        // {
        //     UpdateViewState(args.NewState, args.Active);
        // }
         private void OnStateChanged(object sender, (ItemStack, bool) e)
        {
            UpdateViewState(e.Item1,e.Item2);
        }
    }
}
